#include "stdafx.h"
#include "dispTestObject.h"
#include "dispIdManager.h"
#include "java.h"
#include "jtf.h"
#include "jniString.h"
#include <string>
#include <sstream>

BSTR CDispTestObject::ToString()
{
  std::wstringstream ss;
  JtfAbstractTestObjectClass jtfAbstractTestObject;
  JtfObjectHandleClass jtfObjectHandle;
  CJniLocalReference<jobject> jobjJtfHandle = jtfAbstractTestObject.GetHandle.Invoke(mjobjTestObject);
  if (jobjJtfHandle)
  {
    int handle = jtfObjectHandle.GetHandle.Invoke(jobjJtfHandle.Get());
    int spyId = jtfObjectHandle.GetSpyId.Invoke(jobjJtfHandle.Get());
    CJniString className = jtfObjectHandle.GetClassName.Invoke(jobjJtfHandle.Get());
    ss << className.WString() << L"(" << spyId << L":" << handle << L")";
  }
  else
  {
    ss << L"<undefined>";
  }
  return SysAllocString(ss.str().c_str());
}

HRESULT CDispTestObject::InvokeDynamicMethod(const std::wstring& strDispName, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr)
{
  HRESULT hr = E_NOTIMPL;
  if (::_wcsicmp(strDispName.c_str(), L"getMethodList") == 0)
    hr = mJavaReflection.GetMethodList(mjobjTestObject, pvarResult);
  else
    hr = mJavaReflection.InvokeDynamicMethod(mjobjTestObject, strDispName, pdispparams, pvarResult, pexcepinfo, puArgErr);
  return hr;
}

HRESULT CDispTestObject::GetDynamicProperty(const std::wstring& strDispName, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr)
{
  CComVariant vPropertyName(CComBSTR(strDispName.c_str()));
  DISPPARAMS params;
  params.cArgs = 1;
  params.cNamedArgs = 0;
  params.rgdispidNamedArgs = 0;
  params.rgvarg = &vPropertyName;
  return mJavaReflection.InvokeDynamicMethod(mjobjTestObject, L"getProperty", &params, pvarResult, pexcepinfo, puArgErr);
}

HRESULT CDispTestObject::SetDynamicProperty(const std::wstring& strDispName, DISPPARAMS* pdispparams, VARIANT* pvarResult, EXCEPINFO* pexcepinfo, UINT* puArgErr)
{
  CComVariant vArgs[2];
  vArgs[0] = pdispparams->rgvarg[0]; // order of arguments is inverted
  vArgs[1] = CComBSTR(strDispName.c_str());
  DISPPARAMS params;
  params.cArgs = 2;
  params.cNamedArgs = 0;
  params.rgdispidNamedArgs = 0;
  params.rgvarg = vArgs;
  return mJavaReflection.InvokeDynamicMethod(mjobjTestObject, L"setProperty", &params, pvarResult, pexcepinfo, puArgErr);
}
